package binary 
{
	import flash.utils.ByteArray;
	
	/**
	 * ...
	 * @author gcxk721
	 */
	public class QhByteArray extends ByteArray 
	{
		/**
		 * 解读字节数组中的字符集
		 */
		private static const charset : String = "gbk";
		
		public function QhByteArray() 
		{
			super();
		}
		
		/**
		 * 从字节流中读取一个带符号的 64 位整数。
		 * @return
		 */
		protected final function readLong() : Number 
		{
			var rv : Number = 0;
			for (var i : int = 0; i < 8; ++i) 
			{
				var bv : Number = readByte();
				if (i > 0 && bv < 0)
				{
					bv += 256;
				}
				rv *= 256;
				rv += bv;
			}
			return rv;
		}
		
		/**
		 * 写入带符号的64位整数
		 * @param	value
		 */
		protected final function writeLong(value : Number) : void
		{
			if (value >= 0) 
			{
				writeByte(value / 0x100000000000000);
				writeByte(value / 0x1000000000000);
				writeByte(value / 0x10000000000);
				writeByte(value / 0x100000000);
				writeByte(value >> 24);
				writeByte(value >> 16);
				writeByte(value >> 8);
				writeByte(value);
			}
			else 
			{
				var abs:Number = Math.abs(value);
				var msi:Number = 0x100000000 - Math.abs(abs / 0x100000000);
				if (msi == 0x100000000)
				{
					msi = 0xFFFFFFFF;
				}
				var lsi:Number = 0x100000000 - (abs % 0x100000000);
				writeByte(msi >> 24);
				writeByte(msi >> 16);
				writeByte(msi >> 8);
				writeByte(msi);
				writeByte(lsi >> 24);
				writeByte(lsi >> 16);
				writeByte(lsi >> 8);
				writeByte(lsi);
			}
		}
		
		/**
		 * 从字节流中读取一串字符串
		 * @return
		 */
		public final function readString() : String
		{
			//读取字符长度
			var len : int = readInt();
			return readMultiByte(len, charset);
		}
		
		/**
		 * 在字节流中写入一个字节。
		 * @param	value
		 */
		public final function writeString(value : String) : void
		{
			var bytes : ByteArray = new ByteArray();
			bytes.writeMultiByte(value, charset);
			writeInt(bytes.length);
			writeBytes(bytes, 0, bytes.length);
		}
		
	}

}